from copy import copy
from urllib import urlencode



def unicodeStringEncoding(value):
    try:
        if isinstance(value, basestring):
            return value.encode('utf-8')
    except UnicodeDecodeError:
        try:
            return value.decode('utf-8').encode('utf-8')
        except:
            return value
    
    return value
        

def unicodeParameterEncoding(params):
    for k,v in params.iteritems():
            if isinstance(v,basestring):
                params[k] = unicodeStringEncoding(v)
            elif isinstance(v, list):
                params[k] = []
                for sv in v:
                    params[k].append(unicodeStringEncoding(sv))
    
    return params

def handleUrlParams(_base, _remove=[], _replace=True, **params):
    p = _base.copy()
    
    if _replace:
            p.update(params)
    else:
        for k,v in params.iteritems():
            if not isinstance(v,list):
                v = [v]
            
            if not k in p:
                p[k] = []
            elif not isinstance(p[k],list):
                p[k] = [p[k]]
            else:
                p[k] = copy(p[k])
            p[k].extend(v)
    
    for r in _remove:
        try:
            key,value = r
        except:
            key = r
            value = None
        
        if key in p:
            if isinstance(p[key],list) and value:
                p[key] = copy(p[key])
                p[key].remove(value)
            else:
                del p[key]
    
    return urlencode(unicodeParameterEncoding(p),True)
    